﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ProductKeyManager.Search
{
    /// <summary>
    /// Extension methods for searching
    /// </summary>
    public static class SearchExtensionMethods
    {
        /// <summary>
        /// Calculates the similarity.
        /// </summary>
        /// <param name="search">The search.</param>
        /// <param name="source">The source.</param>
        /// <param name="result">The result.</param>
        public static void CalculateSimilarity(this string search, string source, ref decimal result)
        {
            result = search.CalculateSimilarity(source);
        }

        /// <summary>
        /// Calculates the similarity.
        /// </summary>
        /// <param name="search">The search.</param>
        /// <param name="source">The source.</param>
        /// <returns>The result</returns>
        public static decimal CalculateSimilarity(this string search, string source)
        {
            if (source.Length >= 0)
            {
                if (search.Equals(source))
                {
                    return 1m;
                }

                decimal similarlen = 0m;

                string[] words = search.Split(' ');
                foreach (string word in words)
                {
                    if (source.Contains(word))
                    {
                        similarlen += word.Length;
                    }
                }

                return similarlen / source.Length;
            }
            return 0m;
        }
    }
}
